package xiao_jin.fantastic_journey.client;

import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.client.rendering.v1.EntityRendererRegistry;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.util.Identifier;
import xiao_jin.fantastic_journey.api.capability.CapabilityPayload;
import xiao_jin.fantastic_journey.client.Item.ModModelPredicateProviderRegistry;
import xiao_jin.fantastic_journey.client.hud.Mana;
import xiao_jin.fantastic_journey.core.common.entity.client.MonsterEyeRenderer;
import xiao_jin.fantastic_journey.core.init.ModEntities;
import xiao_jin.fantastic_journey.util.ModUtil;

@Environment(EnvType.CLIENT)
public final class FantasticJourneyClient implements ClientModInitializer {
    public void onInitializeClient() {
        ClientEvent.registerEventAndRender();

        registerNetwork();
        EntityRendererRegistry.register(ModEntities.MONSTER_EYE_ENTITY, MonsterEyeRenderer::new);
        HudRenderCallback.EVENT.invoker();
        HudRenderCallback.EVENT.register((Mana::render));
        ModModelPredicateProviderRegistry.registerCustomModelData();
    }

    private void registerNetwork() {
        PayloadTypeRegistry.playS2C().register(CapabilityPayload.PAYLOAD_ID, CapabilityPayload.CODEC);
        PayloadTypeRegistry.playC2S().register(CapabilityPayload.PAYLOAD_ID, CapabilityPayload.CODEC);

        ClientPlayNetworking.registerGlobalReceiver(CapabilityPayload.PAYLOAD_ID, (pl, context) ->
                context.client().execute(() -> clientPacket(pl.getCapName(), context.player(), pl)));
    }

    private void clientPacket(Identifier id, ClientPlayerEntity player, CapabilityPayload payload) {
        ModUtil.registerCapability(id, payload, player.PC$getOrCreateNBTTagCompound(), player);
    }
}
